package com.cloudcc.mobile.view.web;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.cloudcc.cloudframe.bus.EventEngine;
import com.cloudcc.cloudframe.util.LogUtils;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.AppContext;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.dialog.CallLogLoadingDialog;
import com.cloudcc.mobile.manager.RunTimeManager;
import com.cloudcc.mobile.manager.UrlManager;
import com.cloudcc.mobile.util.Tools;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.view.activity.BeauInfoActivity;
import com.cloudcc.mobile.view.activity.BindActivity;
import com.cloudcc.mobile.view.dynamic.RelevantActivtiy;
import com.cloudcc.mobile.weight.CustomProgressDialog;
import com.litesuits.android.log.Log;

public class Newwebview1 extends Activity {

private String mEns = RunTimeManager.getInstance().getlanguage();
	private WebView webview;
	protected String mUrl = StringUtils.EMPTY;
	// Context mContext;
	private String newurl;
	private boolean _isVisible;// 控制bindtoken影响的问题
	protected CallLogLoadingDialog mProgress;
	public static Newwebview1 instance = null;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newworkwebview);
		instance = this;
		mProgress = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
		webview = (WebView) findViewById(R.id.newworkweb);
		webview.requestFocus();
		webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);// 防止滑动的时候闪屏
		mUrl = AppContext.urlString;
		String urls = getIntent().getStringExtra("url");
		if(urls != null && !TextUtils.isEmpty(urls)){
			mUrl = urls;
		}
		webview.loadUrl(mUrl);
		webview.reload();

		WebSettings webstting = webview.getSettings();
		webstting.setJavaScriptEnabled(true);
		webstting.setAllowFileAccess(true);
		webstting.setSupportZoom(true);
		webstting.setCacheMode(WebSettings.LOAD_DEFAULT);// 是否缓存
		webstting.setBlockNetworkImage(false);
		webstting.setJavaScriptCanOpenWindowsAutomatically(true);

		webstting.setDomStorageEnabled(true);
		webstting.setDatabaseEnabled(true);
		webstting.setDatabasePath(this.getApplicationContext().getCacheDir()
				.getAbsolutePath());

		/** 使webview自己处理打开网页事件，不调用系统浏览器打开 */
		// webview.setWebViewClient(new WebViewClient() {
		// @Override
		// public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// view.loadUrl(url);
		// return true;
		// }
		// // @Override
		// // public void onPageStarted(WebView view, String url, Bitmap
		// favicon) {
		// //
		// // LogUtils.d("webview", "开始加载url" + url);
		// //// showProgress();
		// //
		// // super.onPageStarted(view, url, favicon);
		// // }
		// //
		// // @Override
		// // public void onPageFinished(WebView view, String url) {
		// // LogUtils.d("webview", "加载完成url" + url);
		// //
		// //
		// //// stopProgress();
		// // super.onPageFinished(view, url);
		// // }
		// });
		setListener();
	}

	@Override
	protected void onPause() {
		_isVisible = false;

		super.onPause();
	}

	@Override
	protected void onResume() {
		_isVisible = true;
		super.onResume();
	}

	protected void showProgress() {
		if (_isVisible) {
			if (mProgress == null) {
				mProgress = new CallLogLoadingDialog(this,R.style.DialogLoadingTheme);
				mProgress.show();
				mProgress.settext(getString(R.string.loading));
			}
			if (mProgress != null) {
				mProgress.setCancelable(true);
				mProgress.setCanceledOnTouchOutside(false);
				mProgress.show();
			}
		}
	}

	/**
	 * 停止进度条
	 */
	protected void stopProgress() {
		if (_isVisible && mProgress != null) {
			try {
				mProgress.dismiss();
				mProgress = null;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void setListener() {
		Log.d("webview", "webview" + mUrl);
		// TODO Auto-generated method stub
		// webview.loadUrl("http://www.sogou.com");

		// webview.setWebViewClient(new WebViewClient() {
		// public boolean shouldOverrideUrlLoading(WebView view, String url) {
		// Log.d("webview", "webview"+url);
		// if (UrlManager.isWapLogin(url)) {// 跳转去登录
		// EventEngine.register(DetailFragment.this);
		// Intent intent = new Intent(getActivity(), BindActivity.class);
		// startActivity(intent);
		// return true;
		// }else{
		// view.loadUrl(url);
		// return true;
		// }
		//
		// }
		// });
		// webview.reload();
		// WebSettings webstting = webview.getSettings();
		// webstting.setJavaScriptEnabled(true);
		// webstting.setAllowFileAccess(true);
		// webstting.setSupportZoom(true);
		// webstting.setJavaScriptCanOpenWindowsAutomatically(true);
		// webstting.setCacheMode(WebSettings.LOAD_NO_CACHE);// 是否缓存
		webview.setWebViewClient(new WebViewClient() {
			

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {

				LogUtils.d("webview", "开始加载url" + url);
				showProgress();
				if (url.equals(AppContext.indexUrl)) {
					Newwebview1.this.finish();

					return;
				}
				if (url.equals(UrlTools.loginurl)) {
					Intent intent = new Intent(UrlTools.loginurl);
					Newwebview1.this.sendBroadcast(intent);
				}
				super.onPageStarted(view, url, favicon);
			}

			@Override
			public void onPageFinished(WebView view, String url) {
				LogUtils.d("webview", "加载完成url" + url);

				AppContext.isFirst = true;
				webview.setVisibility(View.VISIBLE);
				stopProgress();
				super.onPageFinished(view, url);
			}

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				LogUtils.d("webview", "跳转：" + url);
				if (UrlManager.isWapLogin(url)) {// 跳转去登录
					EventEngine.register(Newwebview1.this);
					Intent intent = new Intent(Newwebview1.this,
							BindActivity.class);
					startActivity(intent);
					return true;
				}
				if (url.contains("/wx_taskquery.action?m=query&id=")) {
					Log.d("ceshiurl", "跳转之前：" + url);
					String id = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							Tools.getCharacterPosition(url, "&", 2));
//					Intent intent = new Intent(NewWebView.this,
//							RelevantActivtiy.class);
//					intent.putExtra("web", id);
//					// intent.putExtra("web.url", UrlManager.getRootUrl()
//					// + UrlTools.getObjectUrl(id));
//					intent.putExtra("web.url", url);
//					startActivity(intent);
					Intent intent = new Intent(Newwebview1.this, BeauInfoActivity.class);
					intent.putExtra("web", id);
					if((id.startsWith("bef"))||((id.startsWith("bfa")))){
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
						intent.putExtra("from", "newwebview");
					}else{
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(id));
					}		
					startActivity(intent);
					
//					NewWebView.this.finish();
					return true;
				} else if (url.contains("/weiquery.action?m=query&id=")) {
					String id = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							url.length());
//					Tools.i("followService", id);
//					Intent intent = new Intent(NewWebView.this,
//							RelevantActivtiy.class);
//					intent.putExtra("web", id);
//					intent.putExtra("web.url",
//							UrlManager.APP_UR + UrlTools.getObjectUrl(id));
//					startActivity(intent);
					
					Intent intent = new Intent(Newwebview1.this, BeauInfoActivity.class);
					intent.putExtra("web", id);
					if((id.startsWith("bef"))||((id.startsWith("bfa")))){
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
					}else{
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(id));
					}		
					startActivity(intent);
					
					return true;
				} else if (url.contains("/weiquery.action?id=")) {
					String type = url.substring(
							Tools.getCharacterPosition(url, "=", 2) + 1,
							url.length());
					Tools.i("followService", type);
					if (type.equals("query")) {
						String id = url.substring(
								Tools.getCharacterPosition(url, "=", 1) + 1,
								url.length() - 8);
						Tools.i("followService", id);
						Intent intent = new Intent(Newwebview1.this,
								RelevantActivtiy.class);
						intent.putExtra("web", id);
						intent.putExtra("web.url",
								UrlManager.APP_UR + UrlTools.getObjectUrl(id));
						startActivity(intent);
						return true;
					}

				}else if(url.contains("wx_taskquery.action?id=")){
					String id = url.substring(
							Tools.getCharacterPosition(url, "=", 1) + 1,
							Tools.getCharacterPosition(url, "&", 1));
					Intent intent = new Intent(Newwebview1.this, BeauInfoActivity.class);
					intent.putExtra("web", id);
					if((id.startsWith("bef"))||((id.startsWith("bfa")))){
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl_z(id));
					}else{
						intent.putExtra("web.url",UrlManager.getRootUrl()+ UrlTools.getObjectUrl(id));
					}		
					startActivity(intent);
					webview.stopLoading();
					return true;
				}else if (url.contains("weixinreportlist.action")) {
					finish();
				}else if(url.contains("weiviewDashboard.action?dashboardId")){
					finish();
				}

				if (UrlManager.isHome(url)) {
					Newwebview1.this.finish();
					return true;
				} else {
					// 自身加载新链接,不做外部跳转
					view.loadUrl(url);
					return true;
				}
			}

			@Override
			public void onReceivedError(WebView view, int errorCode,
					String description, String failingUrl) {
				AppContext.isError = true;
				
				if ("en".equals(mEns)) {
					view.loadUrl("file:///android_asset/html/error.html");
				}else{
					view.loadUrl("file:///android_asset/html/error.html");
			}
			}
		});
	}
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
		webview.loadUrl(newurl);
//		  String message=newConfig.orientation==Configuration.ORIENTATION_LANDSCAPE ? "屏幕设置为：横屏" : "屏幕设置为：竖屏";

//	         Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}
}
